/* Copyright (c) 2009 - 2010 98Labs Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sbal89.map.server;

import static com.sbal89.map.util.BaseUtil.AUTH;
import static com.sbal89.map.util.BaseUtil.DASHBOARD_VIEW;
import static com.sbal89.map.util.BaseUtil.DEF_DATE;
import static com.sbal89.map.util.BaseUtil.DOCLIST;
import static com.sbal89.map.util.BaseUtil.LOGIN_VIEW;
import static com.sbal89.map.util.BaseUtil.MESSAGE;
import static com.sbal89.map.util.BaseUtil.P_RESID;
import static com.sbal89.map.util.BaseUtil.TZ_MANILA;
import static com.sbal89.map.util.BaseUtil.USER;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.expressme.openid.Authentication;

import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.sbal89.map.model.Document;
import com.sbal89.map.model.Msg;
import com.sbal89.map.model.User;
import com.sbal89.map.util.SDAUtil;

@SuppressWarnings("serial")
public class MainServlet extends BaseServlet {
	private HashMap<String, User> users;
	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Authentication auth = (Authentication) session.getAttribute(AUTH);
		User user = (User) session.getAttribute(USER);
		if (auth == null) {
			request.getRequestDispatcher(LOGIN_VIEW).include(request, response);
		} else {
			if (user == null) {
				user = updateUsers(auth, session);
			}
			request.setAttribute(DOCLIST, getDoclist(user.getId() + ""));
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			request.getRequestDispatcher(DASHBOARD_VIEW).include(request,
					response);
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(USER);
		String resid = request.getParameter(P_RESID);
		try {
			Document doc = SDAUtil.getDocByResId(getSprService(), resid, user.getId()+"");
			StringBuffer tr = new StringBuffer();
			tr.append("<tr id='"+doc.getResourceId()+"'>");
			tr.append("<td>"+doc.getTitle()+"</td>");
			tr.append("<td>"+doc.getTypeStr()+"</td>");
			tr.append("<td>");
			tr.append("\n<a href=\"/map?c=sheet&resid="+doc.getResourceId()+"\" target=\"_blank\" title=\"Spreadsheet\"><img src=\"images/dashboard/spreadsheet.png\" /></a>");
			tr.append("\n<a href=\"http://maps-view.electionexchange.ph/"+doc.getType()+".gen?key="+doc.getKey()+"\" target=\"_blank\" title=\"View Map\"><img src=\"images/dashboard/view.png\" /></a>");
			tr.append("\n<a href=\"http://www.gmodules.com/ig/creator?synd=open&url=http://maps-view.electionexchange.ph/"+doc.getType()+"/"+doc.getKey()+"/mapgadget.xml&lang=en\" target=\"_blank\" title=\"Embed Code\"><img src=\"images/dashboard/get_embed.png\" /></a>");
			tr.append("\n<a href='javascript:remove(\""+doc.getResourceId()+"\")' title=\"Delete Map\"><img src=\"images/dashboard/delete.png\" /></a>");
			tr.append("\n</td>");
			tr.append("</tr>");
			response.setContentType("text/plain");
			response.getWriter().print(tr.toString());
			
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void init() {
		try {
			users = SDAUtil.getUsers(getSprService());
			log.info("Users successfully loaded.");
		} catch (AuthenticationException e) {
			log.severe("Failed to authenticate to google spreadsheet service.");
		} catch (IOException e) {
			log.severe("Failed to load users.");
		} catch (ServiceException e) {
			log.severe("Failed to load users.");
		}
	}
	
	private List<Document> getDoclist(String userid) {
		List<Document> doclist = new ArrayList<Document>();
		try {
			doclist = SDAUtil.getDocs(getSprService(), userid);
		} catch (Exception e) {
			log.severe("Unable to get docs/maps for user: " +userid);
			e.printStackTrace();
		}
		return doclist;
	}

	private User toUser(Authentication auth) {
		User user = new User();
		user.setId(users.size()+1);
		String username = auth.getEmail();
		user.setUsername(username);
		if (username.indexOf("yahoo") < 0) {
			user.setEmail(username);
		}
		user.setFullname(auth.getFullname());
		
		TimeZone tz = TimeZone.getTimeZone(TZ_MANILA);
		SimpleDateFormat sdf = new SimpleDateFormat(DEF_DATE);
		sdf.setCalendar(Calendar.getInstance());
		sdf.setTimeZone(tz);
		user.setSignup(sdf.format(new Date()));
		return user;
	}
	
	private User updateUsers(Authentication auth, HttpSession session) {
		String username = auth.getEmail();
		User user = toUser(auth);
		String msg = "";
		if (users.get(username) == null) {
			try {
				SDAUtil.addNewUser(getSprService(), user);
				log.info("New user added.");
			} catch (MalformedURLException e) {
				log.severe("Adding of new user to user-accounts failed.");
				e.printStackTrace();
			} catch (IOException e) {
				log.severe("Adding of new user to user-accounts failed.");
				e.printStackTrace();
			} catch (ServiceException e) {
				log.severe("Adding of new user to user-accounts failed.");
				e.printStackTrace();
			}
			users.put(user.getUsername(), user);
			msg = "Thank you " + user.getFullname() + " for registering! To create a map click the add button.";
		} else {
			user = users.get(username);
			msg = "Welcome back " + user.getFullname() + ".";
		}
		session.setAttribute(MESSAGE, new Msg(Msg.TYPE_NORMAL,msg));
		session.setAttribute(USER, user);
		return user;
	}
	
}
